package com.bbcare.plat.redis.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.plat.redis.service.IPatientQueueRedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

/*
 * @name:         患者相关信息redis缓存接口实现
 * @author:       DemonLee
 * @createTime:   2017.4.20
 * @description:  患者相关信息缓存接口实现
 * @modify:
 *
 */

@Service
public class PatientQueueRedis implements IPatientQueueRedis {

    // @Resource(name = "jedis")
    // private ShardedJedisClientImpl jedis;

    // public static int cacheFlag = 0;// redis相关数据库表初始化标志

    /*
     * private void initFunc() { // 患者相关缓存数据使用1号分区
     * jedis.setDbIndex(Constants.REDIS_DB_INDEX_PATIENT); }
     */

    // 队列新增患者(按天/总数）
    public void patientAddforQueue(String queueId, Jedis jedis) throws Exception {
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException("111222", "使用redis缓存时，入参值为空!"));
        }

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_QUEUE_KEY);
        inList.add(queueId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            // 非第一次记录，只增加值
            jedis.incr(dayKey);
        } else {
            // 第一次记录，设置时常为3600秒
            jedis.incr(dayKey);
            jedis.expire(dayKey, 24 * 3600);
        }

        // 按队列总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_QUEUE_KEY);
        toList.add(queueId);
        String totalKey = ToolUtils.assembleKey(toList);
        jedis.incr(totalKey);
    }

    // 获取队列新增患者(按天/总数）
    public Map<String, Object> getPatientAddByQueueId(String queueId, Jedis jedis) throws Exception {

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_QUEUE_KEY);
        inList.add(queueId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);

        String dayData = null;
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            dayData = jedis.get(dayKey);
        }

        // 按队列总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_QUEUE_KEY);
        toList.add(queueId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_DAY, dayData);
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 登录账号新增患者（按天/总数）
    public void patientAddforAuthor(String authorId, Jedis jedis) throws Exception {
        if (null == authorId || "".equals(authorId)) {
            throw (new AppException("111222", "使用redis缓存时，入参值为空!"));
        }

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_AUTHOR_KEY);
        inList.add(authorId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            // 非第一次记录，只增加值
            jedis.incr(dayKey);
        } else {
            // 第一次记录，设置时常为3600秒
            jedis.incr(dayKey);
            jedis.expire(dayKey, 24 * 3600);
        }

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        jedis.incr(totalKey);
    }

    // 获取登录账号新增患者（按天/总数）
    public Map<String, Object> getPatientAddByAuthorId(String authorId, Jedis jedis) throws Exception {

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_AUTHOR_KEY);
        inList.add(authorId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);

        String dayData = null;
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            dayData = jedis.get(dayKey);
        }

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_DAY, dayData);
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 租户新增患者（按天/总数）
    public void patientAddforTenant(String tenantId, Jedis jedis) throws Exception {
        if (null == tenantId || "".equals(tenantId)) {
            throw (new AppException("111222", "使用redis缓存时，入参值为空!"));
        }

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_TENANT_KEY);
        inList.add(tenantId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            // 非第一次记录，只增加值
            jedis.incr(dayKey);
        } else {
            // 第一次记录，设置时常为3600秒
            jedis.incr(dayKey);
            jedis.expire(dayKey, 24 * 3600);
        }

        // 按租户总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_TENANT_KEY);
        toList.add(tenantId);
        String totalKey = ToolUtils.assembleKey(toList);
        jedis.incr(totalKey);
    }

    // 获取租户新增患者（按天/总数）
    public Map<String, Object> getPatientAddByTenantId(String tenantId, Jedis jedis) throws Exception {

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PATIENT_DAY_ADD_BY_TENANT_KEY);
        inList.add(tenantId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);

        String dayData = null;
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            dayData = jedis.get(dayKey);
        }

        // 按租户总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PATIENT_TOTAL_ADD_BY_TENANT_KEY);
        toList.add(tenantId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_DAY, dayData);
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 登录账号门诊患者（按天/总数）
    public void ptDoorAddforAuthor(String authorId, Jedis jedis) throws Exception {
        if (null == authorId || "".equals(authorId)) {
            throw (new AppException("111222", "使用redis缓存时，入参值为空!"));
        }

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.DOOR_PT_DAY_ADD_BY_AUTHOR_KEY);
        inList.add(authorId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            // 非第一次记录，只增加值
            jedis.incr(dayKey);
        } else {
            // 第一次记录，设置时常为3600秒
            jedis.incr(dayKey);
            jedis.expire(dayKey, 24 * 3600);
        }

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.DOOR_PT_TOTAL_ADD_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        jedis.incr(totalKey);
    }

    // 获取登录账号门诊数量（按天/总数）
    public Map<String, Object> getPatientDoorByAuthorId(String authorId, Jedis jedis) throws Exception {

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.DOOR_PT_DAY_ADD_BY_AUTHOR_KEY);
        inList.add(authorId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);

        String dayData = null;
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            dayData = jedis.get(dayKey);
        }

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.DOOR_PT_TOTAL_ADD_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_DAY, dayData);
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 获取登录账号失访数量（按天/总数）
    public Map<String, Object> getPatientLostByAuthorId(String authorId, Jedis jedis) throws Exception {

        // 按天统计
        String currDay = DateUtil.getCurrDate();
        List<String> inList = new ArrayList<String>();
        inList.add(Constants.PT_DAY_LOST_BY_AUTHOR_KEY);
        inList.add(authorId);
        inList.add(currDay);
        String dayKey = ToolUtils.assembleKey(inList);

        String dayData = null;
        Boolean flag = jedis.exists(dayKey);
        if (flag) {
            dayData = jedis.get(dayKey);
        }

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PT_TOTAL_LOST_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_DAY, dayData);
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 获取登录账号随访期总数量（按天/总数）
    public Map<String, Object> getWindowPtTotalByAuthorId(String authorId, Jedis jedis) throws Exception {

        // 按账号总数统计
        List<String> toList = new ArrayList<String>();
        toList.add(Constants.PT_TOTAL_WINDOW_BY_AUTHOR_KEY);
        toList.add(authorId);
        String totalKey = ToolUtils.assembleKey(toList);
        String totalData = null;
        Boolean flag = jedis.exists(totalKey);
        if (flag) {
            totalData = jedis.get(totalKey);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put(Constants.REDIS_DATA_TOTAL, totalData);

        return retMap;
    }

    // 新增队列今日诊疗门诊患者(按天）
    public void saveOutPatientRedisforQueue(Map<String, Object> mapIn, Jedis jedis) throws Exception {
        String queueId = (String) mapIn.get("queueId");
        String dealDate = (String) mapIn.get("dealDate");
        String userId = (String) mapIn.get("userId");
        String ptSchemeId = (String) mapIn.get("ptSchemeId");
        // String userName = (String) mapIn.get("userName");
        Integer dealTime = (Integer) mapIn.get("dealTime");// 时间转换成数字作为集合元素的分值排序依据

        List<String> inList = new ArrayList<String>();
        String strKey = "";
        inList.add(Constants.REDIS_KEY_FOR_QUEUE_OUTPATIENT_TODAY);
        inList.add(queueId);
        inList.add("" + Constants.SCHEME_BUSI_TYPE_1);
        inList.add(dealDate);
        strKey = ToolUtils.assembleKey(inList);

        // userId※ptSchemeId
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append(userId);
        strBuffer.append(Constants.SPLIT_STR);
        strBuffer.append(ptSchemeId);
        // strBuffer.append(Constants.SPLIT_STR);
        // strBuffer.append(userName);

        jedis.zadd(strKey, dealTime, strBuffer.toString());
        jedis.expire(strKey, 24 * 3600);

        return;
    }

    // 查询队列今日诊疗门诊患者(按天）
    public Map<String, Object> getOprInfoFromRedis(Map<String, Object> mapIn, Jedis jedis) throws Exception {
        Map<String, Object> outMap = new HashMap<String, Object>();
        String strKey = (String) mapIn.get("strKey");
        Integer start = (Integer) mapIn.get("start");
        Integer end = (Integer) mapIn.get("end");

        Tuple tuple = new Tuple("", 0.0);
        Set<Tuple> strInfoSet = jedis.zrevrangeWithScores(strKey, start, end);
        Iterator<Tuple> it = strInfoSet.iterator();
        String patientId = "";
        String ptSchemeid = "";
        String dealTime = "";
        String tempTime = "";
        String elementStr = "";
        long iScore = 0;
        StringBuffer strBuffer = new StringBuffer();
        List<Map<String, Object>> pqsList = new ArrayList<Map<String, Object>>();
        while (it.hasNext()) {
            patientId = "";
            ptSchemeid = "";

            Map<String, Object> oprMap = new HashMap<String, Object>();
            tuple = it.next();
            elementStr = tuple.getElement();// userId※ptSchemeId
            String[] elementArr = elementStr.split(Constants.SPLIT_STR);
            if (elementArr.length >= 2) {
                patientId = elementArr[0];
                ptSchemeid = elementArr[1];
            } else {
                continue;
            }

            // 1530-->15:30; 1-->00:01; 957-->09:57
            iScore = (long) tuple.getScore();
            tempTime = String.format("%04d", iScore);// 不足4位，左补0
            strBuffer.setLength(0);
            strBuffer.append(tempTime.substring(0, 2));
            strBuffer.append(Constants.COLON_SPLIT_STR);
            strBuffer.append(tempTime.substring(2));
            dealTime = strBuffer.toString();

            oprMap.put("dealTime", dealTime);
            oprMap.put("ptSchemeid", ptSchemeid);
            oprMap.put("patientId", patientId);
            pqsList.add(oprMap);
        }
        outMap.put("rows", pqsList);

        return outMap;
    }
}
